<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm"  ref="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item prop="key">
        <el-input v-model="dataForm.key" placeholder="姓名/合同编号/合同名称" clearable></el-input>
      </el-form-item>
      <el-form-item prop="contractType">
        <el-select v-model="dataForm.contractType" placeholder="合同类型">
          <el-option
            v-for="item in optionsContractType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="contractStatus">
        <el-select v-model="dataForm.contractStatus" placeholder="合同状态">
          <el-option
            v-for="item in optionsContractStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="resetForm('dataForm')">重置</el-button>
        <el-button
          v-if="isAuth('generator:contractinfo:save')"
          type="primary"
          @click="addOrUpdateHandle()"
        >新增</el-button>
        <!-- <el-button v-if="isAuth('generator:contractinfo:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      :row-class-name="tableRowClassName"
      style="width: 100%;">
      <el-table-column prop="stakeholder" header-align="center" align="center" label="干系人"></el-table-column>
      <el-table-column prop="contractNum" header-align="center" align="center" label="合同编号"></el-table-column>
      <el-table-column prop="contractType" header-align="center" align="center" label="合同类型"></el-table-column>
      <el-table-column prop="contractName" header-align="center" align="center" label="合同名称"></el-table-column>
      <el-table-column prop="startTime" header-align="center" align="center" label="起始时间"></el-table-column>
      <el-table-column prop="endTime" header-align="center" align="center" label="截止时间"></el-table-column>
      <el-table-column prop="timeToExpiration" header-align="center" align="center" label="距离到期时间"></el-table-column>
      <el-table-column prop="contractStatus" header-align="center" align="center" label="合同状态" :formatter="contractStatusFmt"></el-table-column>
      <el-table-column prop="partyA" header-align="center" align="center" label="委托方（甲方）"></el-table-column>
      <el-table-column prop="partyB" header-align="center" align="center" label="受托方（乙方）"></el-table-column>
      <el-table-column prop="signData" header-align="center" align="center" label="签订日期"></el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="editOrUpdateHandle(scope.row.contractId)"
            :style="{ display: visibleAddOrUpdate }"
          >修改</el-button>
          <!-- <el-button type="text" size="small" @click="deleteHandle(scope.row.contractId)">删除</el-button> -->
          <el-button
            type="text"
            size="small"
            @click="renewalHandle(scope.row.contractId)"
            :style="{ display: visibleRenewal }"
          >续签</el-button>
          <el-button
            type="text"
            size="small"
            @click="fileHandle(scope.row.contractId)"
            :style="{ display: visibleFile }"
          >归档</el-button>
          <el-button
            type="text"
            size="small"
            @click="invalidHandle(scope.row.contractId)"
            :style="{ display: visibleInvalid }"
          >作废</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./contractinfo-add-or-update";
export default {
  data() {
    return {
      dataForm: {
        key: ""
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      optionsContractType: [],
      optionsContractStatus: []
    };
  },
  components: {
    AddOrUpdate
  },
  activated() {
    if (this.$route.query.contractid !== undefined) {
      this.getDataListHome();
    } else {
      this.getDataList();
    }
  },
  methods: {
    contractStatusFmt(row) {
      if (row.contractStatus === "归档") {
        this.visibleAddOrUpdate = "none";
        this.visibleFile = "none";
        this.visibleInvalid = "none";
        return (row.contractStatus = row.contractStatus);
      } else if (row.contractStatus === "作废") {
        this.visibleAddOrUpdate = "none";
        this.visibleRenewal = "none";
        this.visibleFile = "none";
        this.visibleInvalid = "none";
        return (row.contractStatus = row.contractStatus);
      } else {
        this.visibleAddOrUpdate = "";
        this.visibleRenewal = "";
        this.visibleFile = "";
        this.visibleInvalid = "";
        return (row.contractStatus = row.contractStatus);
      }
    },
    getDataListHome() {
      var _this = this
      this.$http({
        url: this.$http.adornUrl("/generator/contractinfo/linkContractExpected"),
        method: "get",
        params: this.$http.adornParams({
          contractId: this.$route.query.contractid
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.list.forEach(function(value, index, array) {
            value.timeToExpiration =
              _this.GetNumberOfDays(value.endTime) > 0
                ? _this.GetNumberOfDays(value.endTime)
                : "已过期";
          });
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
      });
    },
    // 获取数据列表
    getDataList() {
      var _this = this;
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/generator/contractinfo/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          key: this.dataForm.key,
          contractType: this.dataForm.contractType,
          contractStatus: this.dataForm.contractStatus
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.list.forEach(function(value, index, array) {
            value.timeToExpiration =
              _this.GetNumberOfDays(value.endTime) > 0
                ? _this.GetNumberOfDays(value.endTime)
                : "已过期";
          });
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });

      this.$http({
        url: this.$http.adornUrl(`/generator/datadictionary/info/${21}`),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.optionsContractType = data && data.code === 0 ? data.list : [];
      });

      this.$http({
        url: this.$http.adornUrl(`/generator/datadictionary/info/${22}`),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.optionsContractStatus = data && data.code === 0 ? data.list : [];
      });
    },
    GetNumberOfDays(date2) {
      //获得天数
      //date1：开始日期，date2结束日期
      var a1 = new Date();
      var a2 = Date.parse(new Date(date2));
      var day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24) + 1); //核心：时间戳相减，然后除以天数
      return day;
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, 0, 1);
      });
    },
    // 修改
    editOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, 0, 0);
      });
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.contractId;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/generator/contractinfo/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    // 续签
    renewalHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, 1);
      });
    },
    // 归档
    fileHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.contractId;
          });
      this.$confirm(`确定归档操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl("/generator/contractinfo/fileHandle"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    // 作废
    invalidHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.contractId;
          });
      this.$confirm(`确定作废操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl("/generator/contractinfo/invalidHandle"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    tableRowClassName({ row, rowIndex }) {
      // console.log(row.contractStatus);
      if (Number(row.timeToExpiration) < 30) {
        return "warning-row caveat-row package_" + row.id;
      }
      if (row.timeToExpiration === "已过期" && row.contractStatus === '有效') {
        return "warning-row caveat-row package_" + row.id;
      }
      return "package_" + row.id;
    }
  }
};
</script>
<style>
.el-table .warning-row {
  background: #fafafa;
}
.el-table .warning-row.caveat-row {
  background: rgba(245, 202, 108, 0.1);
}
</style>